package com.softserveinc.moviedbapp.parser;

import android.util.Log;

import com.softserveinc.moviedbapp.model.Movie;
import com.softserveinc.moviedbapp.util.MovieAppConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class JSONParserMovieBrowse implements IMovieDBMethodBrowseSearch {

	private static final String TAG = JSONParserMovieBrowse.class.getSimpleName();

	@Override
	public List<Movie> parse(final InputStream is) {
		List<Movie> movies = new ArrayList<Movie>();
		String jsonString = JSONHelper.convertStreamToString(is);

		/* start parsing */
		int retrys = MovieAppConstants.RETRY_COUNT;
		while (retrys > 0) {
			try {
				JSONArray jsonArray = new JSONArray(jsonString);

				for (int i = 0; i < jsonArray.length(); i++) {
					Movie movie = new Movie();

					JSONObject jsonMovie = jsonArray.getJSONObject(i);

					/* set easily accessible data */
					movie.setName(jsonMovie.getString("name"));
					movie.setCertification(jsonMovie.getString("certification"));
					movie.setMovieId(jsonMovie.getInt("id"));
					movie.setUrl(jsonMovie.getString("url"));
					movie.setRating(jsonMovie.getDouble("rating"));
					movie.setLastModifiedAt(jsonMovie.getString("last_modified_at"));
					movie.setReleased(jsonMovie.getString("released"));
					movie.setVotes(jsonMovie.getInt("votes"));


					/* get the movie poster url */
					JSONArray posters = jsonMovie.getJSONArray("posters");
					for (int j = 0; j < posters.length(); j++)	{
						JSONObject posterUrlObject = posters.getJSONObject(j).getJSONObject("image");

						if (posterUrlObject.getString("size").equals("thumb")) {
							movie.setThumbPosterUrl(posterUrlObject.getString("url"));
							break;
						}
					}
					movies.add(movie);
					Log.d(TAG, "JSON Parsing succeeded, movie\n" + movie.toString());

				}
				break;

			} catch (JSONException e) {
				retrys--;
				Log.e(TAG, "JSON MOVIE LIST Parsing failed NOTHING FOUND.", e);
				if (retrys == 0) {
					Movie movie = new Movie();
					movie.setName("Nothing found.");
					movie.setCertification("NR");
					movies.add(movie);
					break;
				}
				continue;

			}
		}
		try {
			is.close();
		} catch (IOException e) {
			Log.w(TAG, "unable to close input stream", e);
			e.printStackTrace();
		}
		return movies;
	}

}
